﻿
from db_helper import db_ebook
from get_book_info import get_book_info
from util_tool import safe_download_page

class updater:
	def init(self, db_name = 'itebook.db'):
		self.db = db_ebook()
		self.db.connect_db(db_name)

	def commit(self):
		self.db.conn.commit()

	def import_book_info(self, src_url, book_info):
		if self.db.is_book_exists(src_url):
			return
		info = book_info['info']
		self.db.add_book(src_url, info[0], info[1], info[2], info[3], info[4], info[5], info[6], info[7], info[8], info[9], info[10], info[11], info[12])
		bookid = self.db.get_book_id(src_url)

		tags = book_info['tag']
		for tag in tags:
			if not self.db.is_tag_exists(tag['href']):
				self.db.add_tag(tag['href'], tag['name'])
				self.commit()

		authors = book_info['author']
		for author in authors:
			if not self.db.is_author_exists(author['href']):
				self.db.add_author(author['href'], author['name'])
				self.commit()

		publishers = book_info['publisher']
		for publisher in publishers:
			if not self.db.is_publisher_exists(publisher['href']):
				self.db.add_publisher(publisher['href'], publisher['name'])
				self.commit()

		tagids = []
		for tag in tags:
			tagid = self.db.get_tag_id(tag['href'])
			tagids.append((bookid, tagid))
		self.db.add_book_tag(tagids)

		authorids = []
		for author in authors:
			authorid = self.db.get_author_id(author['href'])
			authorids.append((bookid, authorid))
		self.db.add_book_author(authorids)

		publisherids = []
		for publisher in publishers:
			publisherid = self.db.get_publisher_id(publisher['href'])
			publisherids.append((bookid, publisherid))
		self.db.add_book_publisher(publisherids)
		self.commit()

if __name__ == '__main__':
	id = 177
	update = updater()
	update.init()
	while id <= 2088:
		url = "http://it-ebooks.info/book/%d/" % id
		ss = safe_download_page(url)
		try:
			book_info = get_book_info(ss)
			try:
				update.import_book_info(url, book_info)
			except:
				print 'import book info faild'
		except:
			print 'get_book_info failed'
		id += 1

